import React, { Component } from 'react'
import ReactDOM from 'react-dom/client';
// 类式组件
/*  class Demo extends Component {
  state = { count: 0 }
  myRef = React.createRef()
  increment = () => {
    //函数式的setState
    this.setState(state=> ({ count: state.count + 1 }))
  }
  alertInfo = () => {
    alert(this.myRef.current.value)
  }
  unmount = () =>{
    // react17的!!! (已被弃用,但是依然可以从ReactDom包里导入)
    // ReactDOM.unmountComponentAtNode( document.getElementById('root'))
    // react18!!!
    const container = document.getElementById('root')
    const root = ReactDOM.createRoot(container)
    root.unmount(container)
  }
  componentDidMount(){
    this.timer = setInterval(()=>{
      this.setState(state=> ({ count: state.count + 1 }))
    },1000)
  }
  componentWillUnmount(){
    clearInterval(this.timer)
  }
  render() {
    const { count } = this.state
    return (
      <div>
        <input type="text" ref={this.myRef}/>
        <h1>求和为：{count}</h1>
        <button onClick={this.increment}>点我+1</button>
        <button onClick={this.unmount}>卸载组件</button>
        <button onClick={this.alertInfo}>提示内容</button>
      </div>
    )
  }
} */

// 函数式组件

function Demo() {
  const [count, setCount] = React.useState(0)
  const [name, setName] = React.useState('tom')
  const myRef = React.useRef()
  // 加的回调
  function increment() {
    // setCount(count + 1)
    setCount(count => count + 1)
  }
  function changeName() {
    setName('jack')
  }
  function unmount() {
    // react17的!!! (已被弃用,但是依然可以从ReactDom包里导入)
    // ReactDOM.unmountComponentAtNode(document.getElementById('root'))
    // react18!!!
    const container = document.getElementById('root')
    const root = ReactDOM.createRoot(container)
    root.unmount(container)
  }
  function alertInfo() {
    alert(myRef.current.value)
  }
  React.useEffect(() => {
    let timer = setInterval(() => {
      setCount(count => count + 1)
    }, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [])
  return (
    <div>
      <input type="text" ref={myRef} />
      <h1>求和为：{count}</h1>
      <h1>名字是：{name}</h1>
      <button onClick={increment}>点我+1</button>
      <button onClick={changeName}>点我改名</button>
      <button onClick={unmount}>卸载组件</button>
      <button onClick={alertInfo}>提示内容</button>
    </div>
  )
}

export default Demo